# -*- coding: utf-8 -*-
from flask import Flask, jsonify, request
from flask_cors import CORS
import imgUtil
from Tap import Tap
import db

db.iniDB()
app = Flask(__name__)
CORS(app, supports_credentials=True, origins="*")

@app.route("/", methods=['GET'])
def hello_world():
    pg = ''
    with open('index.html', 'rb') as f:
        pg = f.read()
    return pg

@app.route("/aa", methods=['GET'])
def aa():
    pg = ''
    with open('upload.html', 'rb') as f:
        pg = f.read()
    return pg

@app.route("/reg", methods=['POST'])
def handleReg():
    img64 = request.form['img']
    cnt = request.form['cnt']
    cnt = int(cnt)
    try:
        img = imgUtil.base64_to_img(img64)
    except Exception as e:
        return jsonify({'err': 'bad img'})
    vec = imgUtil.getV(img)
    anslist = db.batchGetTaps(vec, cnt)
    return jsonify({'result':[x.tap.toJson() for x in anslist]})


@app.route("/updateTap", methods=['POST'])
def handleUpdateTap():
    img64 = request.form['img']
    category = request.form['category']
    description = request.form['description']
    try:
        img = imgUtil.base64_to_img(img64)
    except Exception as e:
        return jsonify({'err': 'bad img'})
    vec = imgUtil.getV(img)
    tap = Tap(category, 'data:image/png;base64,'+img64, description, vec)
    db.insertTap(tap)
    return jsonify({'err': 'success'})

app.run(port=9466, debug=True, host='0.0.0.0')